import { useContext, useEffect } from "react";
import { GlobalModel } from "@/ui/context";
import { XHSNote } from "@common/models";
import { getNote, syncMention } from "@/ui/utils/rpc/xhs";
import { useAsyncEffect, useMemoizedFn, useSafeState } from "ahooks";
import { getValueOrDie } from "@common/utils";
import { message } from "antd";

export function useViewModel() {
  const globalModel = getValueOrDie(useContext(GlobalModel));
  const [noteUnreads, setNoteUnreads] = useSafeState<
    Record<XHSNote["noteId"], number>
  >({});

  useEffect(() => {
    const ans: Record<string, number> = {};
    for (const r of globalModel?.mentions?.records ?? []) {
      const noteId = r.item_info.id;
      if (!r.isChecked) {
        if (!ans[noteId]) {
          ans[noteId] = 1;
        } else {
          ans[noteId] += 1;
        }
      }
    }
    setNoteUnreads(ans);
  }, [globalModel?.mentions?.records]);

  useAsyncEffect(async () => {
    const noteMetas: Pick<XHSNote, "noteId" | "xsecToken">[] = [];
    for (const mention of globalModel?.mentions?.records ?? []) {
      const { id, xsec_token } = mention.item_info;
      if (!noteMetas.find((r) => r.noteId === id)) {
        noteMetas.push({
          noteId: id,
          xsecToken: xsec_token,
        });
      }
    }
    const ans: XHSNote[] = [];
    for (const { noteId, xsecToken } of noteMetas) {
      const note = await getNote({
        targetId: globalModel?.sessions[0]?.apps.xhs.targetId,
        noteId,
        xsecToken,
      });
      ans.push(note);
    }
    globalModel.notes = ans;
  }, [globalModel?.mentions?.records]);

  const onNoteClick = (note: XHSNote) => async () => {
    if (!globalModel?.sessions.length) {
      message.error("请先登录账号");
      return;
    }

    const model = getValueOrDie(globalModel);
    if (note.noteId === model.discussion?.note.noteId) {
      return;
    }
    delete model.discussion;

    model.discussion = {
      note,
      ownerId: globalModel!.sessions[0]!.apps.xhs.user!.user_id,
      comments: {
        hasMore: true,
        records: [],
      },
      sendQueue: [],
    };
  };

  const onSyncClick = useMemoizedFn(async () => {
    message.success("开始更新已登录账号的数据");
    globalModel.updating = globalModel.sessions.reduce(
      (ans, cur) => {
        ans[cur.id] = true;
        return ans;
      },
      {} as Record<string, boolean>,
    );

    for (const session of globalModel.sessions) {
      const user = session.apps.xhs.user;
      if (user) {
        syncMention({ sessionId: session.id })
          .then(() => {
            message.success(
              `账号【${session.apps.xhs.user?.nickname}】数据更新完成`,
            );
          })
          .catch((err) => {
            message.error(
              `账号【${session.apps.xhs.user?.nickname}】数据更新异常：${err.message}`,
            );
          })
          .finally(() => {
            getValueOrDie(globalModel.updating)[session.id] = false;
          });
      }
    }
  });

  return { globalModel, onNoteClick, noteUnreads, onSyncClick };
}
